package com.mr.orderclient.message;

import com.fasterxml.jackson.core.type.TypeReference;
import com.mr.orderclient.entity.ProductInfo;
import com.mr.orderclient.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Class: ProductInfoReceiver
 * User (作者):MRui
 * TODO (描述)：消息队列处理类
 * Date 2018-11-11 23:08
 */
@Slf4j
@Component
public class ProductInfoReceiver {

    //redis Key 规则为product_stock_s+productId
    private static final String PRODUCT_STOCK_TEMPLATE = "product_stock_%s";

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
    * User (作者): MRui
    * TODO (描述)：接收product发送到mq中的消息
    * Data：2018-11-11 23:44
    */
    //自动创建队列
    @RabbitListener(queuesToDeclare = @Queue("productInfo"))
    public void process(String message){
        List<ProductInfo> productInfoList = (List<ProductInfo>) JsonUtil.jacksonFromJson(message,
                new TypeReference<List<ProductInfo>>(){});
        log.info("productInfo:【{}】",productInfoList);
        //储存到redis
        for (ProductInfo productInfo: productInfoList){
            redisTemplate.opsForValue().set(String.format(PRODUCT_STOCK_TEMPLATE,productInfo.getProductId()),String.valueOf(productInfo.getProductStock()));
            String s = redisTemplate.opsForValue().get(String.format(PRODUCT_STOCK_TEMPLATE, productInfo.getProductId()));
            log.info("s:【{}】",s);
        }
    }
}
